package org.shagin.jfin.ui.budget.item.impl;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

import org.shagin.jfin.core.CoreUtils;
import org.shagin.jfin.core.Debug;
import org.shagin.jfin.data.model.OperationCategory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings("serial")
public class TreeNodeView extends OperationCategoryView {
    private static final Logger log = LoggerFactory
            .getLogger(TreeNodeView.class);

    /**
     * {@inheritDoc}
     */
    @Override
    public void setBudgetItem(Object budgetItem) {
        Debug.traceEnter(log, budgetItem);
        if (log.isDebugEnabled() && budgetItem != null)
            log.debug("budgetItem.Class:" + budgetItem.getClass().getName());
        this.budgetItem = budgetItem;
        loadTreeNodeOperationRules();
        updateTableUI();
        updateToolbarState();
    }

    /**
     * Load tree node operation rules.
     */
    protected void loadTreeNodeOperationRules() {
        CoreUtils.assertNotNull(operationRules, "operationRules");
        operationRules.clear();
        for (int i = 0; i < getTreeNode().getChildCount(); i++) {
            TreeNode childTreeNode = getTreeNode().getChildAt(i);
            if (childTreeNode instanceof DefaultMutableTreeNode) {
                DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) childTreeNode;
                Object obj = treeNode.getUserObject();
                if (obj != null && obj instanceof OperationCategory) {
                    OperationCategory operationCategory = (OperationCategory) obj;
                    loadOperationRules(operationRules, operationCategory);
                }
            }
        }
    }

    /**
     * Gets the tree node.
     * 
     * @return the tree node
     */
    protected DefaultMutableTreeNode getTreeNode() {
        CoreUtils.assertNotNull(budgetItem, "budgetItem");
        return (DefaultMutableTreeNode) budgetItem;
    }
}
